package manager

import ext.rlog
import manager.ota.OtaServiceManager
import org.json.JSONObject

object VersionManager  {

    private var clientPath = ""

    fun checkUpdate() {
        if (clientPath.isEmpty() || AppManager.isBusy) {
            rlog("机器正忙 不能更新:${clientPath.isEmpty()} ${AppManager.isBusy}")
            return
        }
        rlog("客户端开始更新")
        AppManager.installApk(clientPath)
        clientPath = ""
    }

    fun updateWithServer(json: JSONObject) {
        val curl = json.getString("clientfileUrl")
        if (curl.isNotEmpty()) {
            AsyncTask.post(ClientVersionUpdateTask(curl))
            return
        }

        val murl = json.getString("lowerfileUrl")
        AsyncTask.post(McuOtaUpdateTask(murl))
    }

    private class McuOtaUpdateTask(val url: String): Runnable {

        private fun exec() {
            rlog("开始下载MCU更新文件")
            val datas = NetworkManager.downData(url)
            rlog("MCU下载成功")
            if ( AppManager.isBusy ) {
                rlog("设备忙 不能升级")
                return
            }
            rlog("MCU开始更新")
            OtaServiceManager.Instance.startUpdate(datas, 0)
        }

        override fun run() {
            try {
                exec()
            } catch (e: Exception) {
                e.printStackTrace()
                rlog("MCU更新下载文件失败")
            }
        }

    }

    private class ClientVersionUpdateTask(val url: String) : Runnable {

        private fun exec() {
            rlog("开始下载客户端更新文件")
            val file = NetworkManager.downLoadFile("client.apk", url)
            rlog("客户端下载成功")
            clientPath = file.path
            VersionManager.checkUpdate()
        }

        override fun run() {
            try {
                exec()
            } catch (e: Exception) {
                e.printStackTrace()
                rlog("客户端更新下载文件失败")
            }
        }
    }
}